package com.yang.lesson03;

import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Iterator;

//鼠标监听事件
public class TestMouseListener {
    public static void main(String[] args) {
        new MyFrame("画图");

    }
}

//自己的类
class MyFrame extends Frame{
    //画画需要笔，需要监听鼠标的当前位置，需要集合来存储这个点
    ArrayList points;

    public MyFrame(String title){
        super(title);
        setBounds(200,200,500,500);

        points=new ArrayList<>();
        //鼠标监听器，针对窗口
        this.addMouseListener(new MyMouseListener());

        setVisible(true);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    @Override
    public void paint(Graphics g) {
        //画画
        //监听鼠标的事件
        Iterator iterator = points.iterator();
        while (iterator.hasNext()){
            Point point =(Point) iterator.next();
            g.setColor(Color.orange);
            g.fillOval(point.x,point.y,10,10);
        }
    }

    //添加一个点到页面上的方法
    public void addPaint(Point point){
        points.add(point);
    }
    private class MyMouseListener extends MouseAdapter{
        //鼠标点击，按下，弹起，按住不放

        @Override
        public void mousePressed(MouseEvent e) {
            MyFrame frame =(MyFrame) e.getSource();//接收到对象并进行类型转换
            //获得点击时的坐标
            frame.addPaint(new Point(e.getX(),e.getY()));

            frame.repaint();//刷新
        }
    }
}
